package com.senyin.servlet.position;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.senyin.common.BaseResponse;
import com.senyin.entity.Dept;
import com.senyin.entity.Position;
import com.senyin.service.DeptService;
import com.senyin.service.PositionService;
import com.senyin.service.impl.DeptServiceImpl;
import com.senyin.service.impl.PositionServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

public class PositionShowAllServlet extends HttpServlet {
    private PositionService positionService = new PositionServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        BaseResponse<List<Position>> listBaseResponse = null;
        try {
            listBaseResponse = positionService.showAll();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        resp.setContentType("application/json;charset=utf-8");
        HashMap<String, Object> positions = new HashMap<>();
        try {
            positions.put("code",listBaseResponse.getCode());
            positions.put("msg",listBaseResponse.getMessage());
            positions.put("count",listBaseResponse.getTotal());
            positions.put("data",listBaseResponse.getData());
            resp.getWriter().write(objectMapper.writeValueAsString(positions));
        } catch (Exception e) {
            positions.put("code",-1);
            positions.put("msg","error");
            positions.put("count",0);
            resp.getWriter().write(objectMapper.writeValueAsString(positions));
        }
    }
}
